<script setup lang="ts">
import type { TableColumn } from '@/types'
import type { ListItem, QueryParams } from './type'
import { PAGING } from '@/constant'
import { Plus } from '@element-plus/icons-vue'

import OperateModal from './components/operate-modal.vue'

const modalRef = ref<InstanceType<typeof OperateModal>>()

const loading = ref(false)
const columns: TableColumn<ListItem>[] = [
  { key: uuid(), label: '用能单元', prop: 'pointFull' },
  { key: uuid(), label: '设备类型', prop: 'typeKeyName' },
  { key: uuid(), label: '设备编号', prop: 'num' },
  { key: uuid(), label: '设备名称', prop: 'name' },
  { key: uuid(), label: '设备状态', prop: 'statusName' },
  { key: uuid(), label: '设备使用状态', prop: 'useStatusName' },
  { key: uuid(), label: '设备能效等级', prop: 'efficiencyLevelName' },
]
const tableData = shallowRef([])
const pagination = reactive({
  pageNumber: PAGING.PARAMS.pageNumber,
  pageSize: PAGING.PARAMS.pageSize,
  total: 0,
})
const qs: Partial<QueryParams> = reactive({})

const typeKey = ref<string>()
const equipmentId = ref<number>()
const isViewing = ref(false)

async function handleClickNode(node: any) {
  qs.pointId = node.id
  await nextTick()
  await getTableData()
}

// 判断是否可以新增
async function isAddable(typeKey: string) {
  const res = await equipmentDefinitionInfoApi.getDefinitionList(typeKey)
  return res.data.length > 0
}

async function handleAdd() {
  isViewing.value = false
  equipmentId.value = undefined
  if (qs.typeKey) {
    const isOk = await isAddable(qs.typeKey)
    if (!isOk)
      return
    typeKey.value = qs.typeKey
    await nextTick()
    modalRef.value?.open()
  }
  else {
    ElMessage.warning('请选择设备类型')
  }
}
async function handleView(row: ListItem) {
  isViewing.value = true
  equipmentId.value = row.id
  typeKey.value = row.typeKey
  await nextTick()
  modalRef.value?.open()
}
async function handleEdit(row: ListItem) {
  isViewing.value = false
  equipmentId.value = row.id
  typeKey.value = row.typeKey
  await nextTick()
  modalRef.value?.open()
}
async function handleDelete(row: ListItem) {
  const res = await ElMessageBox.confirm('确定要删除吗？', '提示', { type: 'warning' }).catch(() => {})
  if (res === 'confirm') {
    await equipmentInfoApi.deleteEquipmentInfoById(row.id)
    ElMessage.success('删除成功！')
    await getTableData()
  }
}
async function getTableData() {
  loading.value = true
  try {
    const { data } = await equipmentInfoApi.queryEquipmentInfoByPage({
      ...unref(qs),
      pageNumber: pagination.pageNumber,
      pageSize: pagination.pageSize,
    })
    tableData.value = data.records ?? []
    pagination.total = data.total
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="padding-sm flex container">
    <ReadonlyPointTree
      fire
      class="flex-incompressible"
      @click-node="handleClickNode"
    />
    <div class="flex-direction flex-fillRemaining margin-left-sm overflow flex align-end">
      <view-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :show-toolbox="false"
        border
        row-key="id"
        :operate-width="200"
      >
        <template #actions>
          <div class="flex flex-wrap items-center gap-3">
            <span class="flex-shrink-0 opacity-80">设备类型</span>
            <DictionaryPicker v-model="qs.typeKey" code="SHE_BEI_LEI_XING" placeholder="请选择设备类型" class="free !w-40" />
            <span class="flex-shrink-0 opacity-80">设备编号</span>
            <ElInput v-model="qs.num" class="free !w-40" placeholder="请输入" />
            <span class="flex-shrink-0 opacity-80">设备名称</span>
            <ElInput v-model="qs.name" class="free !w-40" placeholder="请输入" />
            <span class="flex-shrink-0 opacity-80">设备状态</span>
            <DictionaryPicker v-model="qs.status" class="free !w-40" code="YUN_XING_ZHUANG_TAI" placeholder="请选择设备状态" />
            <SearchButton @click="getTableData" />
            <ElButton class="!ml-0" type="success" :icon="Plus" @click="handleAdd">
              新增
            </ElButton>
          </div>
        </template>
        <template #operate="{ row }">
          <ElButton
            type="primary"
            size="small"
            @click="handleView(row)"
          >
            查看
          </ElButton>
          <ElButton
            type="warning"
            size="small"
            @click="handleEdit(row)"
          >
            修改
          </ElButton>
          <ElButton
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            删除
          </ElButton>
        </template>
      </view-table>
      <ListsPagination
        v-model:page-num="pagination.pageNumber"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>

    <OperateModal
      v-if="typeKey && qs.pointId" ref="modalRef"
      :point-id="qs.pointId"
      :type-key="typeKey"
      :equipment-id="equipmentId"
      :is-viewing="isViewing"
      @save-success="getTableData"
    />
  </div>
</template>
